import coverApi from '@/api/cover'
const GANTT_TYPE_NOT_SHOW_BUSSINESS_UNIT = 0
export default {
  data() {
    return {
      fileId: '',
      initervalId: null,
      exportButtonLoading: false,
    }
  },
  beforeDestroy() {
    this.exportButtonLoading = false
    clearInterval(this.initervalId)
    this.initervalId = null
  },
  methods: {
    exportGantt(params) {
      if (this.initervalId) {
        this.$Message.warning({
          content: '之前触发的导出工期图操作正在进行，请稍后再试',
          duration: 3
        });
        return
      }
      console.log('in exportGantt')
      coverApi.requestDownLoadGantt(params).then(res => {
        if (res.data.code == 200) {
          this.exportButtonLoading = true
          this.fileId = res.data.data
          this._checkFileStatus(params)
        } else if (res.data.code == 4009) {
          this.$Message.warning({
            content: res.data.msg || '当前搜索条件下无数据可导出',
            duration: 3
          });
        }
      })
    },
    _checkFileStatus(params) {
      this.initervalId = setInterval(() => {
        console.log('in _checkFileStatus')
        coverApi.checkDownLoadGantt({
          id: this.fileId
        }).then(res => {
          if (res.data.code == 200) {
            if (res.data.data == 1) {
              clearInterval(this.initervalId)
              this.initervalId = null
              this._downloadGantt(params)
            }
          } else {
            clearInterval(this.initervalId)
            this.initervalId = null
            this.exportButtonLoading = false
          }
        })
      }, 5000)
    },
    _downloadGantt(params) {
      console.log('in _downloadGantt')
      coverApi.downLoadGantt({
        id: this.fileId
      }).then(res => {
          const a = document.createElement("a");
          const blob = new Blob([res.data], { type: "image/jpeg;charset=utf-8" });
          a.href = URL.createObjectURL(blob);
          a.style.display = "none";
          if (params.ganttType == GANTT_TYPE_NOT_SHOW_BUSSINESS_UNIT) {
            let trgNode = this.trgnodes ? this.trgnodes: params.trgNode
            a.download = trgNode + '-工期图';
          } else {
            a.download = '数字化转型专项实施方案任务表-汇总工期图'
          }
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
      }).finally(() => {
        this.exportButtonLoading = false
      })
    }
  }
}
